package com.ruoyi.park.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.IdUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.omp.api.RemoteLeaseRecordService;
import com.ruoyi.omp.api.domain.BuiRoom;
import com.ruoyi.omp.api.domain.BuiRoomFacility;
import com.ruoyi.omp.api.domain.FeLeaseRecord;
import com.ruoyi.omp.api.enums.LeaseStateEnum;
import com.ruoyi.park.domain.BuiBuilding;
import com.ruoyi.park.domain.BuiPark;
import com.ruoyi.park.domain.vo.BuiRoomVO;
import com.ruoyi.park.domain.vo.RoomFacilityExcelVO;
import com.ruoyi.park.mapper.BuiBuildingMapper;
import com.ruoyi.park.mapper.BuiParkMapper;
import com.ruoyi.park.mapper.BuiRoomFacilityMapper;
import com.ruoyi.park.mapper.BuiRoomMapper;
import com.ruoyi.park.service.IBuiRoomService;
import com.ruoyi.park.service.manager.LeaseRecordManager;
import com.ruoyi.system.api.LinkFileServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 房源Service业务层处理
 *
 * @author cjie
 * @date 2021-07-20
 */
@Service
public class BuiRoomServiceImpl extends LinkFileServiceImpl implements IBuiRoomService {
    @Autowired
    private BuiRoomMapper buiRoomMapper;
    @Autowired
    private BuiRoomFacilityMapper buiRoomFacilityMapper;

    @Autowired
    private BuiParkMapper buiParkMapper;

    @Autowired
    private BuiBuildingMapper buiBuildingMapper;


/*    @Autowired
    private RemoteLeaseRecordService leaseRecordService;*/

    @Autowired
    private LeaseRecordManager leaseRecordManager;

    /**
     * 查询房源
     *
     * @param id 房源ID
     * @return 房源
     */
    @Override
    public BuiRoom selectBuiRoomById(String id) {
        BuiRoom buiRoom = buiRoomMapper.selectBuiRoomById(id);
        buiRoom.setFileList(getFileList(id));
        BuiRoomFacility buiRoomFacility = new BuiRoomFacility();
        buiRoomFacility.setRoomId(buiRoom.getId());
        buiRoom.setFacilityList(buiRoomFacilityMapper.selectBuiRoomFacilityList(buiRoomFacility));
        //查询公寓租赁
        if(buiRoom.getRoomType().equals("公寓")){

            return buiRoom;
        }
        //查询厂房租赁
        if (StringUtils.isNotEmpty(buiRoom.getRecordId())){
            FeLeaseRecord record = leaseRecordManager.selectFeLeaseRecordById(buiRoom.getRecordId());
            buiRoom.setBeginTime(record.getBeginTime());
            buiRoom.setEndTime(record.getEndTime());
/*            FeLeaseRecord record = new FeLeaseRecord();
            record.setId(buiRoom.getRecordId());
            R<List<FeLeaseRecord>> r = leaseRecordService.listRecord(record);
            if (r.getCode() == R.SUCCESS){
              List<FeLeaseRecord> list =  r.getData();
              if (CollectionUtil.isNotEmpty(list)){
                  FeLeaseRecord FeLeaseRecord = list.get(0);
                  buiRoom.setBeginTime(FeLeaseRecord.getBeginTime());
                  buiRoom.setEndTime(FeLeaseRecord.getEndTime());
              }
            }*/
        }
        return buiRoom;
    }

    /**
     * 查询房源列表
     *
     * @param buiRoom 房源
     * @return 房源
     */
    @Override
    public List<BuiRoom> selectBuiRoomList(BuiRoom buiRoom) {
        if(buiRoom.getRoomType() != null && buiRoom.getRoomType().equals("公寓")){
            return buiRoomMapper.selectBuiRoomApartList(buiRoom);
        }
        return buiRoomMapper.selectBuiRoomList(buiRoom);
    }

    /**
     * 新增房源
     *
     * @param buiRoom 房源
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBuiRoom(BuiRoom buiRoom) {
        buiRoom.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        buiRoom.setCreateTime(DateUtils.getNowDate());
        buiRoom.setCreateBy(SecurityUtils.getUsername());
        if (StringUtils.isEmpty(buiRoom.getState())) {
            buiRoom.setState("闲置");
        }
        if (StringUtils.isEmpty(buiRoom.getLeaseState())) {
            buiRoom.setState("租赁");
        }
        linkFile(buiRoom.getFileIdList(), buiRoom.getId());

        //添加配套设施
        insertRoomFacility(buiRoom);
        return buiRoomMapper.insertBuiRoom(buiRoom);
    }

    private void insertRoomFacility(BuiRoom buiRoom) {
        if (buiRoom.getFacilityList() != null && buiRoom.getFacilityList().size() > 0) {
            buiRoom.getFacilityList().forEach(buiRoomFacility -> {
                buiRoomFacility.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                buiRoomFacility.setRoomId(buiRoom.getId());
                buiRoomFacilityMapper.insertBuiRoomFacility(buiRoomFacility);
            });
        }
    }

    /**
     * 修改房源(内部调用)
     *
     * @param buiRoom 房源
     * @return 结果
     */
    @Override
    public int updateRoom(BuiRoom buiRoom) {
        buiRoom.setUpdateTime(DateUtils.getNowDate());
        buiRoom.setUpdateBy(SecurityUtils.getUsername());
        return buiRoomMapper.updateBuiRoom(buiRoom);
    }

    /**
     * 修改房源
     *
     * @param buiRoom 房源
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateBuiRoom(BuiRoom buiRoom) {
        buiRoom.setUpdateTime(DateUtils.getNowDate());
        buiRoom.setUpdateBy(SecurityUtils.getUsername());

        //如果要修改房源的使用状态，需要判断房源是否已经被租赁，被租赁的房源不可修改使用状态
        if (buiRoom.getState() != null) {
            BuiRoom source = buiRoomMapper.selectBuiRoomById(buiRoom.getId());
            if (!source.getState().equals(buiRoom.getState()) && source.getLeaseState().equals(LeaseStateEnum.已租.getCode())) {
                return AjaxResult.error("房源已出租，不可更改使用状态");
            }
        }

        linkFile(buiRoom.getFileIdList(), buiRoom.getId());

        if (buiRoom.getFacilityList() != null && buiRoom.getFacilityList().size() > 0) {
            buiRoomFacilityMapper.deleteBuiRoomFacilityByRoomId(buiRoom.getId());

            insertRoomFacility(buiRoom);
        }

        return buiRoomMapper.updateBuiRoom(buiRoom) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除房源
     *
     * @param ids 需要删除的房源ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBuiRoomByIds(String[] ids) {
        deleteLinkFile(ids);
        return buiRoomMapper.deleteBuiRoomByIds(ids);
    }

    /**
     * 删除房源信息
     *
     * @param id 房源ID
     * @return 结果
     */
    @Override
    public int deleteBuiRoomById(String id) {
        return buiRoomMapper.deleteBuiRoomById(id);
    }

    /**
     * 通过租赁记录id统计租赁总面积
     *
     * @param recordId 租赁记录id
     * @return
     */
    @Override
    public BigDecimal sumAreaByRecordId(String recordId) {
        return buiRoomMapper.sumAreaByRecordId(recordId);
    }

    /**
     * 通过租赁记录id统计房屋数量
     *
     * @param recordId 记录id
     * @return
     */
    @Override
    public Integer countRoomByRecordId(String recordId) {
        return buiRoomMapper.countRoomByRecordId(recordId);
    }

    @Override
    public String importData(List<BuiRoomVO> buiRoomVOList) {
        if (StringUtils.isNull(buiRoomVOList) || buiRoomVOList.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;

        buiRoomVOList = buiRoomVOList.stream().filter(o -> StringUtils.isNotBlank(o.getHouseNumber())).collect(Collectors.toList());
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BuiRoomVO buiRoomVO : buiRoomVOList) {
            try {
                this.insertDataB(buiRoomVO);
                successNum++;
                //successMsg.append("<br/>" + successNum + "、记录 " + buiRoomVO.getRoomNum() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、记录 " + buiRoomVO.getParkNum() + buiRoomVO.getBuildingNum() + buiRoomVO.getFloor() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importFacilityData(List<RoomFacilityExcelVO> facilityExcelVOS) {
        if (StringUtils.isNull(facilityExcelVOS) || facilityExcelVOS.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        StringBuilder failureMsg = new StringBuilder();
        facilityExcelVOS = facilityExcelVOS.stream().filter(o -> StringUtils.isNotBlank(o.getRoomCode())).collect(Collectors.toList());
        Map<String, List<RoomFacilityExcelVO>> listMap = facilityExcelVOS.stream().collect(Collectors.groupingBy(RoomFacilityExcelVO::getRoomCode));
        for (Map.Entry<String, List<RoomFacilityExcelVO>> entry : listMap.entrySet()) {
            // 查询房源编号是否存在
            BuiRoom query = new BuiRoom();
            query.setRoomNum(entry.getKey());
            List<BuiRoom> list = buiRoomMapper.selectBuiRoomList(query);
            if (list.size() > 0) {
                // 删除改房源下的配套
                BuiRoom room = list.get(0);
                buiRoomFacilityMapper.deleteBuiRoomFacilityByRoomId(room.getId());
                // 插入配套
                entry.getValue().forEach(o -> {
                    BuiRoomFacility facility = new BuiRoomFacility();
                    facility.setFacilityName(o.getFacilityName());
                    facility.setFacilityModal(o.getFacilityModal());
                    facility.setQuantity(o.getQuantity());
                    facility.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                    facility.setRoomId(room.getId());
                    facility.setParkId(room.getParkId());
                    buiRoomFacilityMapper.insertBuiRoomFacility(facility);
                });
            } else {
                String msg = entry.getKey() + "，";
                failureMsg.append(msg);
            }
        }
        String result = failureMsg.toString();
        if (StringUtils.isNotBlank(result)) {
            result  = result + "房源不存在";

            return result;
        }
        return "导入成功";
    }

    private void insertDataB(BuiRoomVO buiRoomVO) {
        //查询园区编号，不存在 插入园区数据；
        if (StringUtils.isBlank(buiRoomVO.getHouseNumber())){
            return;
        }

        BuiPark buiPark = buiParkMapper.selectBuiParkByParkNum(buiRoomVO.getParkNum());
/*        if (StringUtils.isNull(buiPark)) {
            buiPark = new BuiPark();
            buiPark.setParkNum(buiRoomVO.getParkNum());
            buiPark.setParkName(buiRoomVO.getParkName());
            buiPark.setParkAddress(buiRoomVO.getParkAddress());
            buiPark.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            buiPark.setCreateTime(DateUtils.getNowDate());
            buiPark.setCreateBy(SecurityUtils.getUsername());
            buiParkMapper.insertBuiPark(buiPark);
        }*/
        //查询楼栋编号，不存在 插入楼栋编号;
        BuiBuilding buiBuilding = buiBuildingMapper.selectBuiBuildingByNumAndPark(buiPark.getId(), buiRoomVO.getBuildingNum());
        if (StringUtils.isNull(buiBuilding)) {
            buiBuilding = new BuiBuilding();
            buiBuilding.setBuildingNum(buiRoomVO.getBuildingNum());
            buiBuilding.setBuildingName(buiRoomVO.getBuildingName());
            //buiBuilding.setBuildingAddress(buiRoomVO.getBuildingAddress());
            buiBuilding.setParkId(buiPark.getId());
            buiBuilding.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            buiBuilding.setCreateTime(DateUtils.getNowDate());
            buiBuilding.setCreateBy(SecurityUtils.getUsername());
            buiBuildingMapper.insertBuiBuilding(buiBuilding);
        }
        //生成房源编号
        buiRoomVO.setBuildingId(buiBuilding.getId());
        buiRoomVO.setParkId(buiPark.getId());
        buiRoomVO.setRoomNum(buiRoomVO.getParkNum() + "-" + buiRoomVO.getBuildingNum() + "-" + buiRoomVO.getFloor() + "-" + buiRoomVO.getHouseNumber());

        //插入房源
        BuiRoom buiRoom = new BuiRoom();
        BeanUtil.copyProperties(buiRoomVO, buiRoom);
        BuiRoom buiRoom1 = new BuiRoom();
        buiRoom1.setRoomNum(buiRoomVO.getRoomNum());
        List<BuiRoom> list = buiRoomMapper.selectBuiRoomList(buiRoom1);
        if(list == null || list.size()== 0){
            buiRoom.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
/*            if (buiRoom.getLeaseState().equals("是")) {
                buiRoom.setLeaseState("1");
            } else {
                buiRoom.setLeaseState("0");
            }*/
            buiRoom.setCreateTime(DateUtils.getNowDate());
            buiRoom.setCreateBy(SecurityUtils.getUsername());
            this.insertBuiRoom(buiRoom);
        }else {
            buiRoom = list.get(0);
            buiRoomVO.setId(buiRoom.getId());
            BeanUtil.copyProperties(buiRoomVO, buiRoom);
            buiRoom.setUpdateTime(DateUtils.getNowDate());
            buiRoom.setUpdateBy(SecurityUtils.getUsername());
            buiRoomMapper.updateBuiRoom(buiRoom);

        }

    }

    private void insertData(BuiRoomVO buiRoomVO) {
        //查询园区编号，不存在 插入园区数据；
        if (StringUtils.isBlank(buiRoomVO.getHouseNumber())){
            return;
        }

        BuiPark buiPark = buiParkMapper.selectBuiParkByParkNum(buiRoomVO.getParkNum());
        if (StringUtils.isNull(buiPark)) {
            buiPark = new BuiPark();
            buiPark.setParkNum(buiRoomVO.getParkNum());
            buiPark.setParkName(buiRoomVO.getParkName());
            buiPark.setParkAddress(buiRoomVO.getParkAddress());
            buiPark.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            buiPark.setCreateTime(DateUtils.getNowDate());
            buiPark.setCreateBy(SecurityUtils.getUsername());
            buiParkMapper.insertBuiPark(buiPark);
        }
        //查询楼栋编号，不存在 插入楼栋编号;
        BuiBuilding buiBuilding = buiBuildingMapper.selectBuiBuildingByNumAndPark(buiPark.getId(), buiRoomVO.getBuildingNum());
        if (StringUtils.isNull(buiBuilding)) {
            buiBuilding = new BuiBuilding();
            buiBuilding.setBuildingNum(buiRoomVO.getBuildingNum());
            buiBuilding.setBuildingName(buiRoomVO.getBuildingName());
            //buiBuilding.setBuildingAddress(buiRoomVO.getBuildingAddress());
            buiBuilding.setParkId(buiPark.getId());
            buiBuilding.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            buiBuilding.setCreateTime(DateUtils.getNowDate());
            buiBuilding.setCreateBy(SecurityUtils.getUsername());
            buiBuildingMapper.insertBuiBuilding(buiBuilding);
        }
        //生成房源编号
        buiRoomVO.setBuildingId(buiBuilding.getId());
        buiRoomVO.setParkId(buiPark.getId());
        buiRoomVO.setRoomNum(buiRoomVO.getParkNum() + "-" + buiRoomVO.getBuildingNum() + "-" + buiRoomVO.getFloor() + "-" + buiRoomVO.getHouseNumber());

        //插入房源
        BuiRoom buiRoom = new BuiRoom();
        BeanUtil.copyProperties(buiRoomVO, buiRoom);
        BuiRoom buiRoom1 = new BuiRoom();
        buiRoom1.setRoomNum(buiRoomVO.getRoomNum());
        List<BuiRoom> list = buiRoomMapper.selectBuiRoomList(buiRoom1);
        if(list == null || list.size()== 0){
            buiRoom.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            if (buiRoom.getLeaseState().equals("是")) {
                buiRoom.setLeaseState("1");
            } else {
                buiRoom.setLeaseState("0");
            }
            buiRoom.setCreateTime(DateUtils.getNowDate());
            buiRoom.setCreateBy(SecurityUtils.getUsername());
            this.insertBuiRoom(buiRoom);
        }else {
            buiRoom = list.get(0);
            buiRoomVO.setId(buiRoom.getId());
            BeanUtil.copyProperties(buiRoomVO, buiRoom);
            buiRoom.setUpdateTime(DateUtils.getNowDate());
            buiRoom.setUpdateBy(SecurityUtils.getUsername());
            buiRoomMapper.updateBuiRoom(buiRoom);

        }

    }
}
